package com.htstar.ovms.device.controller;


import com.htstar.ovms.admin.api.feign.EtpInfoFeign;
import com.htstar.ovms.admin.api.vo.EtpInfoSVo;
import com.htstar.ovms.common.core.constant.CommonConstants;
import com.htstar.ovms.common.core.i18n.MsgCode;
import com.htstar.ovms.common.core.util.R;
import com.htstar.ovms.common.minio.service.MinioTemplate;
import com.htstar.ovms.common.security.util.SecurityUtils;
import com.htstar.ovms.device.api.dto.CarSecurityAlarmDTO;
import com.htstar.ovms.device.api.entity.ExportRecord;
import com.htstar.ovms.device.handle.event.AlarmExcelExportEvent;
import com.htstar.ovms.device.service.ExportRecordService;
import io.minio.MinioClient;
import io.swagger.annotations.ApiOperation;
import jdk.nashorn.internal.ir.annotations.Ignore;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationEventPublisher;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import springfox.documentation.annotations.ApiIgnore;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Slf4j
@RestController
@AllArgsConstructor
@RequestMapping("/HugeExcel")
@ApiIgnore
public class HugeExcelExportController {

    @Autowired
    MinioTemplate minioTemplate;

    @Autowired
    private EtpInfoFeign etpInfoFeign;

    @Autowired
    private ExportRecordService exportRecordService;

    @Autowired
    private ApplicationEventPublisher publisher;

    @ApiOperation(value = "大量导出报警数据报表", notes = "大量导出报警数据报表")
    @PostMapping("/alarm")
    public R hugeExcelExportAlarm(@RequestBody CarSecurityAlarmDTO carSecurityAlarmDTO) {
        Integer etpId = SecurityUtils.getUser().getEtpId();
        if (carSecurityAlarmDTO.getEtpId() == null) carSecurityAlarmDTO.setEtpId(etpId);
        List<EtpInfoSVo> currentAndParents1 = etpInfoFeign.getCurrentAndParents1(carSecurityAlarmDTO.getEtpId());
        currentAndParents1.forEach(etpInfoSVo -> {
            carSecurityAlarmDTO.setEtpIds(etpInfoSVo.getIds());
        });
        ServletRequestAttributes servletRequestAttributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        RequestContextHolder.setRequestAttributes(servletRequestAttributes, true);//设置子线程共享

        //save export record
        ExportRecord exportRecord = new ExportRecord();
        exportRecord.setEtpId(etpId);
        exportRecord.setExportType(3);
        exportRecord.setExportStatus(1);
        exportRecord.setUserId(SecurityUtils.getUser().getId());
        DateTimeFormatter dtf2 = DateTimeFormatter.ofPattern("yyyy-MM-dd_HH-mm-ss");
        String fileName = "安防警报_" + SecurityUtils.getUser().getId() + "_" + dtf2.format(LocalDateTime.now());
        exportRecord.setExportName(fileName);
        exportRecordService.save(exportRecord);
        carSecurityAlarmDTO.setExportId(exportRecord.getId());
        carSecurityAlarmDTO.setUserId(SecurityUtils.getUser().getId());
        carSecurityAlarmDTO.setFileName(fileName);
        try {
            publisher.publishEvent(new AlarmExcelExportEvent(this, carSecurityAlarmDTO));
        } catch (Exception e) {
            log.error("发布警情报表导出错误");
        }

        return R.ok(MsgCode.EXPORTING.msg());
    }

    @PostMapping("/upload")
    public R uploadExcel() {
        String bucketName = "ovms";
        minioTemplate.createBucket(bucketName);
        MinioClient minioClient = minioTemplate.getMinioClient();
        FileInputStream fileInputStream = null;
        try {
            fileInputStream = new FileInputStream(new File("AlarmExcel/1/安防警报_1_2021-01-13_09-40-41.xlsx"));
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }

//        String fileName = IdUtil.simpleUUID() + StrUtil.DOT + FileUtil.extName(file.getOriginalFilename());
        String fileName = "安防警报_1_2021-01-13_09-40-41.xlsx";
        Map<String, String> resultMap = new HashMap<>(4);
//		resultMap.put("bucketName", CommonConstants.BUCKET_NAME);
        resultMap.put("bucketName", bucketName);
        resultMap.put("fileName", fileName);
        resultMap.put("url", String.format("/admin/sys-file/%s/%s", CommonConstants.BUCKET_NAME, fileName));

        try {
            minioTemplate.putObject(bucketName, fileName, fileInputStream);
            //文件管理数据记录,收集管理追踪文件
//            fileLog(file, fileName);
        } catch (Exception e) {
            log.error("上传失败", e);
            return R.failed(e.getLocalizedMessage());
        }
        return R.ok(resultMap);
    }
}
